#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django import forms
from models import Document

from documents.models import Faculty, Module, ModuleTerm, ModulePart, Item
from django.forms.models import ModelForm
from documents.formfields import FullNameField

class DocumentForm(ModelForm):
    """
    Form for Documents
    """

    class Meta:
        model = Document
        fields = ('name', 'tags', 'description')

    def save(self, commit=True):
        """
        Make sure the document doesn't get saved twice
        this is done here because it should be seemless
        """
        documents = self.instance.module_part.document_set.filter(name__iexact=self.cleaned_data.get("name"), module_term = self.instance.module_term)
        # test for a duplicate entry by one user; if there is one: return it without doing anything
        if documents.exists() and self.instance.pk == None:
            self.instance = documents.iterator().next()
            return self.instance
            
        return super(DocumentForm, self).save(commit)
        
    
class ItemForm(ModelForm):
    """
    Form for Items
    """
    
    class Meta:
        model = Item
        fields = ('comment', 'item_category', )
        
#    def save(self, commit=True):
#        """
#        Makes sure the ItemCategory gets created
#        """
##        try:
##            item_category = ItemCategory.objects.get(name__iexact = self.cleaned_data['item_category'])
##        except ItemCategory.DoesNotExist:
##            item_category = ItemCategory(name = self.cleaned_data['item_category'])
##        
##        
##        item_category.save()
#        item_category, _ = ItemCategory.objects.get_or_create(name__iexact = self.cleaned_data['item_category'])
#            
#        self.instance.item_category = item_category
#        
#        #do ye good olde stuff
#        return super(ItemForm, self).save(commit)

class FacultyForm(ModelForm):
    """
    Form for a Faculty
    """
    
    class Meta:
        model = Faculty
        fields = ('name', )

    def clean_name(self):
        """
        Make sure there is no faculty with that name
        """
        name = self.cleaned_data["name"]
        
        # test for a duplicate entry
        if Faculty.objects.filter(name__iexact = name).exists():
            raise forms.ValidationError("Es existiert bereits ein Fachbereich mit diesem Namen.")
            return

        return name
    

class ModuleForm(ModelForm):
    """
    Form for a Module
    """
    class Meta:
        model = Module
        fields = ('name', )
    
    def clean_name(self):
        """
        Make sure there is no module with that name and faculty
        """
        
        name = self.cleaned_data["name"]
        
        # Ignore some funny guy entering the same name (the pk is already existent)
        if self.instance.pk and name == self.instance.name:
            return name        
        
        # test for a duplicate entry
        if self.instance.faculty.module_set.filter(name__iexact=name).exists():
            raise forms.ValidationError("Es existiert bereits eine Veranstaltung mit diesem Namen.")
            return

        return name
    
class ModuleTermForm(ModelForm):
    """
    Form for ModuleTerm
    """
    
    lecturer = FullNameField(widget = forms.TextInput, max_length = 128)
    
    class Meta:
        model = ModuleTerm
        fields = ('semester', )
        
    def clean(self):
        """
        Make sure there is no module term duplicate
        """
        try:
            (first_name, last_name) = self.cleaned_data["lecturer"]
        except KeyError: 
            return self.cleaned_data
        semester = self.cleaned_data["semester"]
        
        # Ignore some funny guy entering the same (the pk is already existent)
        if (self.instance.pk and (semester == self.instance.semester) and (first_name == self.instance.lecturer.first_name) and (last_name == self.instance.lecturer.last_name)):
            return self.cleaned_data  
        
        if ModuleTerm.objects.filter(semester = semester, lecturer__first_name = first_name, lecturer__last_name = last_name, module = self.instance.module).exists():
            raise forms.ValidationError("Es existiert bereits ein Semester mit diesem Dozenten.")
            return
        
        return self.cleaned_data

class ModulePartForm(ModelForm):
    """
    Form for a ModulePart
    """
    
    class Meta:
        model = ModulePart
        fields = ('name', )

    def clean_name(self):
        """
        Make sure there is no module part with that name and faculty
        """
        
        name = self.cleaned_data["name"]
        
        # Ignore some funny guy entering the same name (the pk is already existent)
        if self.instance.pk and name == self.instance.name:
            return name
        
        # test for a duplicate entry
        if self.instance.module.modulepart_set.filter(name__iexact=name).exists():
            raise forms.ValidationError("Es existiert bereits ein Teil des Moduls mit diesem Namen.")
            return

        return name
    
